//
//  QXSlidingButton.m
//  PassengerFramework
//
//  Created by Qianxia on 2017/1/5.
//  Copyright © 2017年 不完美的艺术. All rights reserved.
//

#import "QXSlidingButton.h"


@interface QXSlidingButton ()

@property (strong, nonatomic) UIView *sliderView;
@property (strong, nonatomic) UIImageView *iconImageView;
@property (strong, nonatomic) UIView *dragView;
@property (assign, nonatomic) BOOL reached;
@end

@implementation QXSlidingButton

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupViews];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self setupViews];
}

- (void)setupViews {
    if (!self.sliderView) {
        if (self.offsetX == 0) {
            self.offsetX = 15;
        }
        
//        CGFloat imageWidth = self.iconImage.size.width;
//        if (imageWidth == 0) {
//            imageWidth = 20;
//        }
        CGFloat imageWidth = 20;
        self.iconImageView = [[UIImageView alloc] init];
        self.titleLabel = [[UILabel alloc] init];
        self.sliderView = [[UIView alloc] init];
        self.sliderView.backgroundColor = [UIColor clearColor];
        self.dragView = [[UIView alloc] init];
        self.dragView.backgroundColor = [UIColor clearColor];
        
        [self addSubview:self.sliderView];
        [self.sliderView addSubview:self.dragView];
        [self.sliderView addSubview:self.iconImageView];
        [self.sliderView addSubview:self.titleLabel];
        
        NSDictionary *viewsDictionary = @{@"sliderView": self.sliderView, @"iconImageView": self.iconImageView, @"titleLabel": self.titleLabel, @"dragView": self.dragView};
        
        self.sliderView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[sliderView]|" options:0 metrics:nil views:viewsDictionary]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[sliderView]|" options:0 metrics:nil views:viewsDictionary]];
        
        self.iconImageView.translatesAutoresizingMaskIntoConstraints = NO;
        self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
        self.dragView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(x)-[iconImageView(width)]" options:0 metrics:@{@"width": @(imageWidth), @"x": @(self.offsetX)} views:viewsDictionary]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[titleLabel]|" options:0 metrics:nil views:viewsDictionary]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.iconImageView attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[titleLabel]|" options:0 metrics:nil views:viewsDictionary]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[dragView(width)]" options:0 metrics:@{@"width": @(CGRectGetWidth([UIScreen mainScreen].bounds) - 10)} views:viewsDictionary]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[dragView]|" options:0 metrics:nil views:viewsDictionary]];
        
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        panGestureRecognizer.minimumNumberOfTouches = 1;
        [self.dragView addGestureRecognizer:panGestureRecognizer];
    }
    
    self.iconImageView.image = self.iconImage;
    self.titleLabel.text = self.title;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.textColor = self.textColor;
}

- (void)setIconImage:(UIImage *)iconImage {
    _iconImage = iconImage;
    
    self.iconImageView.image = iconImage;
}

- (void)setTitle:(NSString *)title {
    _title = title;
    self.titleLabel.text = title;
}

- (void)setTextColor:(UIColor *)textColor {
    _textColor = textColor;
    self.titleLabel.textColor = textColor;
}

- (void)panAction:(UIPanGestureRecognizer *)panGesture {
    CGPoint translatedPoint = [panGesture translationInView:self.sliderView];
    CGRect frame = self.sliderView.frame;
    frame.origin.x = translatedPoint.x;
    
    self.sliderView.frame = frame;
    
    if (panGesture.state == UIGestureRecognizerStateEnded) {
        
        CGFloat velocityX = [panGesture velocityInView:self].x * 0.2;
        CGFloat finalX = translatedPoint.x + velocityX;
        if (finalX < 0) {
//            finalX = 0;
        } else if (finalX + CGRectGetMinX(self.dragView.frame) > CGRectGetWidth(self.frame) - 50) {
            // 固定 成功
            self.reached = YES;
            [self doneAction];
        }
        
        CGFloat animationDuration = fabs(velocityX * 0.0002) + 0.2;
        [UIView transitionWithView:self duration:animationDuration options:UIViewAnimationOptionCurveEaseOut animations:^{
        } completion:^(BOOL finished) {
            if (finished) {
                [self animationFinished];
            }
        }];
    }
}

- (void)animationFinished {
    if (!self.reached) {
        [self reset];
    }
}

- (void)reset {
    [UIView transitionWithView:self duration:0.2 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.sliderView.frame = CGRectMake(0, 0, CGRectGetWidth(self.sliderView.frame), CGRectGetHeight(self.sliderView.frame));
    } completion:^(BOOL finished) {
        if (finished) {
            self.reached = NO;
        }
    }];
}

- (void)doneAction {
//    self.dragView.userInteractionEnabled = NO;
    [UIView transitionWithView:self duration:0.2 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.sliderView.frame = CGRectMake(0, 0, CGRectGetWidth(self.sliderView.frame), CGRectGetHeight(self.sliderView.frame));
    } completion:^(BOOL finished) {
        
        if (finished) {
            // 主线程执行
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.doneHandler) {
                    self.doneHandler();
                    [self resetButton];
                }
            });
        }
    }];
}

- (void)resetButton {
    self.reached = NO;
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
